﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.EntityFrameworkCore.Storage;

namespace Jack.EntityFrameworkCore
{
    internal class TransactionManager : IDisposable, IAsyncDisposable
    {
        public DbTransaction DbTransaction { get; }

        public TransactionManager(DbTransaction dbTransaction)
        {
            DbTransaction = dbTransaction;
        }

        public void Commit()
        {
            DbTransaction.Commit();
        }

        public async Task CommitAsync(CancellationToken cancellationToken = default)
        {
            await DbTransaction.CommitAsync(cancellationToken);
        }

        public void Rollback()
        {
            DbTransaction.Rollback();
        }

        public async Task RollbackAsync(CancellationToken cancellationToken = default)
        {
            await DbTransaction.RollbackAsync(cancellationToken);
        }

        public void Dispose()
        {
            DbTransaction.Dispose();
        }

        public ValueTask DisposeAsync()
        {
            return DbTransaction.DisposeAsync();
        }

        public static TransactionManager CreateInstance<TDbContext>(TDbContext dbContext)
            where TDbContext : JackDbContext<TDbContext>
        {
            return new TransactionManager(dbContext.Database.BeginTransaction().GetDbTransaction());
        }
    }
}
